package novel.common.web;
import com.alibaba.fastjson.JSON;
import novel.common.constant.IConstInfo;
import novel.common.page.PageParam;
import novel.common.utils.DateUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.util.Date;

/**
 * Created by 苏同 on 2016/10/6.
 */
public class BaseController {
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());


    public PageParam getPageParam(HttpServletRequest request) {
        String size = request.getParameter("pageSize"); // 每页行数
        String Num = request.getParameter("pageNum"); // 当前页码

        int pageSize = IConstInfo.PAGE_SIZE;
        if(!StringUtils.isEmpty(size)) {
            pageSize = Integer.parseInt(size);
        }
        int pageNum = IConstInfo.PAGE_NUM;
        if(!StringUtils.isEmpty(Num)){
            pageNum = Integer.parseInt(Num);
        }
        return new PageParam(pageNum,pageSize);
    }

    /**
     * 返回结果JSON字符串
     * @param result
     * @param message
     * @return
     */
    protected String renderResult(String result, StringBuilder message) {
        return renderResult(result, message != null ? message.toString() : "");
    }

    /**
     * 返回结果JSON字符串
     * @param result
     * @param message
     * @return
     */
    protected String renderResult(String result, String message) {
        @SuppressWarnings("unused")
        class CustomResultClass{
            private String result;
            private String message;
            public CustomResultClass(String result, String message){
                this.result = result;
                this.message = message;
            }
            public String getResult() {
                return result;
            }
            public void setResult(String result) {
                this.result = result;
            }
            public String getMessage() {
                return message;
            }
            public void setMessage(String message) {
                this.message = message;
            }
        }
        return JSON.toJSONString(new CustomResultClass(result, message));
    }

    /**
     * 客户端返回结果JSON字符串
     * @param response
     * @param result
     * @param message
     * @return
     */
    protected String renderResult(HttpServletResponse response, String result, String message) {
        return renderString(response, renderResult(result, message), "json");
    }

    /**
     * 客户端返回JSON字符串
     * @param response
     * @param object
     * @return
     */
    protected String renderString(HttpServletResponse response, Object object) {
        return renderString(response, JSON.toJSONString(object), "application/json");
    }

    /**
     * 客户端返回字符串
     * @param response
     * @param string
     * @return
     */
    protected String renderString(HttpServletResponse response, String string, String type) {
        try {
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
            return null;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 初始化数据绑定
     * 1. 将所有传递进来的String进行HTML编码，防止XSS攻击
     * 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
//			@Override
//			public String getAsText() {
//				Object value = getValue();
//				return value != null ? DateUtils.formatDateTime((Date)value) : "";
//			}
        });
    }
}
